<template>
  <div class="user-container">
    <div class="search" v-show="isShowSearch">
      <span>姓名 </span>
      <el-input placeholder="请输入姓名" v-model="selectData.realName"/>
      <span>用户类型 </span>
      <el-select placeholder="请选择用户类型" v-model="selectData.userType">
        <el-option v-for="item in userType" :value="item.value" :label="item.label"></el-option>
      </el-select>
      <span>所属租户 </span>
      <el-input placeholder="请输入所属租户" v-model="selectData.tenantName"/>
      <span>所属部门 </span>
      <el-input placeholder="所属部门" v-model="selectData.deptName"/>
      <el-button class="el-button__primary" type="primary" @click="initUserTableData">
        <template #icon>
          <el-icon>
            <Search/>
          </el-icon>
        </template>
        查询
      </el-button>
      <el-button class="el-button__default" @click="refresh()">
        <template #icon>
          <el-icon>
            <Refresh/>
          </el-icon>
        </template>
        重置
      </el-button>
    </div>
    <!--  操作按钮-->
    <div class="operation">
      <div class="float_left">
        <el-button class="el-button__primary" type="primary" @click="userStore1.setUserInsertOpen(true)">
          <template #icon>
            <svg-icon icon-class="add"/>
          </template>
          新增
        </el-button>
        <el-button class="el-button__plain" @click="userStore1.setOpenUpload(true)">
          <template #icon>
            <svg-icon icon-class="cloud-upload"/>
          </template>
          导入
        </el-button>
        <el-button :class="selectedIds.length!==0?'el-button__plain':'el-button__plain__disabled'"
                   @click="deleteRoleBatch()" :disabled="selectedIds.length===0">
          <template #icon>
            <el-icon>
              <Delete/>
            </el-icon>
          </template>
          删除
        </el-button>
      </div>
      <div class="float_right">
        <el-tooltip :content="isShowSearch?'隐藏搜索':'显示搜索'" placement="top">
          <el-button circle @click="isShowSearch=!isShowSearch">
            <template #icon>
              <el-icon>
                <Search/>
              </el-icon>
            </template>
          </el-button>
        </el-tooltip>
        <el-tooltip content="刷新" placement="top">
          <el-button circle @click="refresh">
            <template #icon>
              <el-icon>
                <Refresh/>
              </el-icon>
            </template>
          </el-button>
        </el-tooltip>
      </div>
    </div>
    <el-table
        row-key="id"
        border
        class="user-table"
        :data="tableData"
        v-loading="loading"
        :header-cell-class-name="'table-header'"
        :cell-class-name="'cell'"
        highlight-current-row
        default-expand-all
        fit
        label="use show-overflow-tooltip"
        show-overflow-tooltip
        @selection-change="handleSelectionChange"
    >
      <el-table-column type="selection" :selectable="selectable" width="65"/>
      <el-table-column label="#" prop="id" width="200px">
      </el-table-column>
      <el-table-column label="登录名" prop="loginName" width="150">
      </el-table-column>
      <el-table-column label="姓名" prop="realName" width="150">
      </el-table-column>
      <el-table-column label="身份证号码" prop="idCard" width="150">
      </el-table-column>
      <el-table-column label="性别" prop="sex" width="150">
        <template #default="scope">
          <el-tag :type="scope.row.sex===null?'danger':'primary'" size="large" style="width: 60px">
            {{ scope.row.sex === null ? '未知' : scope.row.sex === 0 ? '男' : '女' }}
          </el-tag>
        </template>
      </el-table-column>
      <el-table-column label="用户类型" prop="userType" width="150">
        <template #default="scope">
          <el-tag type="success" size="large">
            {{ scope.row.userType === null ? '未知' : userType[scope.row.userType].label }}
          </el-tag>
        </template>
      </el-table-column>
      <el-table-column label="手机号" prop="phone" width="150">
      </el-table-column>
      <el-table-column label="邮箱" prop="email" width="150">
      </el-table-column>
      <el-table-column label="状态" prop="status" width="150">
        <template #default="scope">
          <el-tag :type="scope.row.status===0?'primary':'danger'" size="large">
            {{ statusInfo[scope.row.status].label }}
          </el-tag>
        </template>
      </el-table-column>
      <el-table-column label="所属部门" prop="deptName" width="150">
      </el-table-column>
      <el-table-column label="所属租户" prop="tenantName" width="150">
      </el-table-column>
      <el-table-column prop="operator" label="操作" width="250" fixed="right">
        <template #default="scope">
          <el-button link size="small" class="role-table__operator" v-if="scope.row.loginName!=='admin'"  @click="handleRestPassword({id:scope.row.id,loginName:scope.row.loginName})">
            <template #icon>
              <svg-icon icon-class="update"/>
            </template>
            重置密码
          </el-button>
          <el-button link size="small" class="role-table__operator" @click="handleUpdateUser(scope.row.id)" v-if="scope.row.loginName!=='admin'">
            <template #icon>
              <svg-icon icon-class="update"/>
            </template>
            修改
          </el-button>
          <el-button link size="small" class="role-table__operator" :disabled="deleteDisabled(scope.row.loginName)"
                     @click="deleteUser(scope.row.id)">
            <template #icon>
              <svg-icon icon-class="delete"/>
            </template>
            删除
          </el-button>
        </template>
      </el-table-column>
    </el-table>
    <div class="pagination">
      <div class="pagination-block">
        <el-pagination
            v-model::current-page="currentPage"
            v-model:page-size="pageSize"
            :page-sizes="[6,10,20,30,40,50]"
            layout="total, sizes, prev, pager, next, jumper"
            :total="total"
            @current-change="handleCurrentChange"
            @size-change="handleSizeChange"
        />
      </div>
    </div>
    <add-user @refresh="refresh"/>
    <upload @refresh="refresh"/>
  </div>
</template>
<script setup lang="ts">

import {Delete, Refresh, Search} from "@element-plus/icons-vue";
import SvgIcon from "@/components/SvgIcon/index.vue";
import {onMounted, ref} from "vue";
import type {RolePageVO} from "@/api/role/types.ts";
import { deleteRoleById, deleteRoleByIdBatch} from "@/api/role";
import Upload from "@/components/user/upload.vue";
import {roleStore} from "@/stores/role/roleStore.ts";
import {userStore} from "@/stores/user/userStore.ts";
import AddRole from "@/components/role/addRole.vue";
import {ElMessage, ElMessageBox} from "element-plus";
import GrantRole from "@/components/role/grantRole.vue";
import {deleteUserById, deleteUserByIdBatch, getUserList, resetPassword} from "@/api/user";
import AddUser from "@/components/user/addUser.vue";

const loading = ref(false)
const isShowSearch = ref(true)
const total = ref(0)
const pageSize = ref(10)
const currentPage = ref(1)
const tableData = ref([])
const selectData = ref({
  realName: "",
  userType: null,
  deptName: "",
  tenantName: ""
})
const selectedIds = ref([] as number[])
const selectable = (row) => !['admin'].includes(row.loginName)
const deleteDisabled = (loginName: string) => ['admin'].includes(loginName)
const userType = ref([
  {label: '系统用户', value: 0},
  {label: '教师', value: 1},
  {label: '学生', value: 2}
])
const statusInfo = ref([
  {label: '正常', value: 0},
  {label: '停用', value: 1},
])
const store = roleStore()
const userStore1= userStore()
onMounted(() => {
  initUserTableData()
})
/**
 * 初始化表单信息
 */
const initUserTableData = async () => {
  loading.value = true
  const res = await getUserList({
    userType: selectData.value.userType,
    tenantName: selectData.value.tenantName,
    deptName: selectData.value.deptName,
    realName: selectData.value.realName,
    page: currentPage.value,
    pageSize: pageSize.value
  })
  tableData.value = res.data["records"]
  total.value = res.data["total"]
  currentPage.value = res.data['current']
  pageSize.value = res.data['size']
  loading.value = false
}
/**
 * 刷新页面
 */
const refresh = () => {
  currentPage.value = 1
  pageSize.value = 10
  selectData.value = {
    realName: "",
    userType: null,
    deptName: "",
    tenantName: ""
  }
  initUserTableData()
}
const handleCurrentChange = (val: number) => {
  currentPage.value = val
  initUserTableData()
}
const handleSizeChange = (val: number) => {
  pageSize.value = val
  initUserTableData()
}
const handleSelectionChange = (val: RolePageVO[]) => {
  selectedIds.value = val.map(item => item.id)
}
const handleGrant = (id: number) => {
  store.setGrantRoleId(id)
  store.setGrantPage(true)
}
/**
 * 打开修改页面
 */
const handleUpdateUser = (id) => {
  userStore1.setUpdateUserId(id)
  userStore1.setUserInsertOpen(true)
}

const handleRestPassword=(data)=>{
  ElMessageBox.confirm(
      '确定重置用户密码吗?',
      '提示', {
        app: undefined, components: undefined, config: undefined, directives: undefined, mixins: [], provides: undefined,
        confirmButtonText: '确定',
        cancelButtonText: '取消',
        type: 'warning'
      }
  ).then(async () => {
    const res =await resetPassword(data)
      ElMessage.success("修改成功")
  }).catch(() => {
  })
}
/**
 * 删除角色
 * @param id
 */
const deleteUser = (id) => {
  ElMessageBox.confirm(
      '此操作将永久删除该用户, 是否继续?',
      '提示', {
        app: undefined,
        components: undefined,
        config: undefined,
        directives: undefined,
        mixins: [],
        provides: undefined,
        confirmButtonText: '确定',
        cancelButtonText: '取消',
        type: 'warning'
      }
  ).then(async () => {
    const res = await deleteUserById(id)
    ElMessage.success("删除成功")
    refresh()
  }).catch(() => {
  })
}

/**
 * 批量删除角色
 */
const deleteRoleBatch = () => {
  if (selectedIds.value.length === 0) {
    ElMessage.warning("请选择要删除的角色")
    return
  }
  ElMessageBox.confirm(
      '此操作将永久删除选中的角色, 是否继续?',
      '提示', {
        app: undefined,
        components: undefined,
        config: undefined,
        directives: undefined,
        mixins: [],
        provides: undefined,
        confirmButtonText: '确定',
        cancelButtonText: '取消',
        type: 'warning'
      }
  ).then(async () => {
    const res = await deleteUserByIdBatch(selectedIds.value)
    ElMessage.success("删除成功")
    selectedIds.value = []
    refresh()
  }).catch(() => {
  })
}
</script>
<style scoped>
.user-container {
  border: 1px solid var(--el-menu-border-color);
  width: 87.5vw;
  display: flex;
  flex-direction: column;
  padding: 20px;
}

.search {
  span {
    line-height: 32px;
  }

  display: flex;
  font-size: 12px;

  .el-input {
    width: 160px;
    height: 32px;
    font-size: 12px;
    margin: 0 10px;
  }

}
.search {
  display: flex;
  font-size: 12px;
}
.search span {
  line-height: 32px;
}
.el-input,.el-select  {
  width: 160px;
  height: 32px;
  font-size: 12px;
  margin: 0 8px;
}

.operation {
  width: 100%;
  height: 10%;
  justify-content: space-between;
  text-align: center;
  align-items: center;
  display: flex;

  .float_left {
    align-items: center;
    display: flex;
  }

  .float_right {
    align-items: center;
    display: flex;
    margin-right: 20px;
  }
}

.pagination {
  width: 100%;
  height: 10%;
  display: flex;
  justify-content: right;

  .pagination-block {
    margin-right: 20px;
  }
}

:deep(.table-header) {
  color: #000000;
  font-size: 1.5vh;
  text-align: center;
}

.user-table {
  margin: 10px 0 20px 0;
}

.el-table {
  --el-table-row-hover-bg-color: rgb(245, 247, 250);
  --el-table-header-bg-color: rgb(245, 247, 250);
}

.el-tag--dark, .el-tag--dark.el-tag--primary {
  --el-tag-bg-color: rgb(46, 92, 246);
  color: #ffffff;
}

.el-tag.el-tag--primary {
  --el-tag-text-color: rgb(46, 92, 246);
}

.el-tag--plain, .el-tag--plain.el-tag--primary {
  --el-tag-border-color: rgb(46, 92, 246);
}

:deep(.cell) {
  text-align: center;
  margin: 10px 0;
}

:deep(.role-table__operator.disable) {

  font-size: 14px;
}

.el-button.is-link {
  --el-button-text-color: rgb(46, 92, 246);
  --el-button-disabled-text-color: rgb(150, 173, 250);
  --el-button-active-text-color: rgb(46, 92, 246);
}

.el-button.is-link:not(.is-disabled):active, .el-button.is-link:not(.is-disabled):hover {
  color: rgb(46, 92, 246);
}
</style>